package com.ittx.dzt.meione.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.OrderGetDTO;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.meione.handler.AbstractBaseMeioneApiHandler;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.json.JacksonTool;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据订单号下载订单详情
 * <p>
 * cy.salesOrder.download.byOrderId
 * /erp/un/sys/order/v2 批量查询发货单-V2
 * 增量接口当指定单号用
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/8/27
 */
@Slf4j
@Service
public class MeioneSalesOrderDownloadByIdService extends AbstractBaseMeioneApiHandler<OrderGetDTO> {

	@Override
	public String getMeioneMethod() {
		return "/erp/un/sys/order/v2";
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SALESORDER_DOWNLOAD_BY_ORDERID;
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		// 参数校验
		Result<?> result = checkParams(platformApiParamDTO, orderGetDTO);
		if (result.hasError()) {
			return result;
		}
		List<Object> list = new ArrayList<>();
		String[] orderCodeArr = orderGetDTO.getOrderId().split(",");
		for (String code : orderCodeArr) {
			result = this.getOrderById(platformApiParamDTO, code);
			if (result.hasError()) {
				return result;
			}
			Object resultData = result.getData();
			// 同步返回
			if (orderGetDTO.getIsAsync() == 0) {
				list.add(resultData);
			} else {
				platformApiParamDTO.setPlatformIdentifierTag(code);
				result = this.sendRequestToPlatform(platformApiParamDTO, resultData, true);
				if (!result.isSuccess()) {
					return result;
				}
			}
		}
		// 同步返回
		if (orderGetDTO.getIsAsync() == 0) {
			return Result.success().addData(list).addMsg(platformApiParamDTO.getStoreConfig().getChainUniqueCode());
		}
		return Result.success();
	}


	/**
	 * 根据id获取订单
	 *
	 * @param platformApiParamDTO
	 * @param id
	 * @return
	 */
	public Result<?> getOrderById(PlatformApiParamDTO platformApiParamDTO, String id) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.getOrderBySdk(platformApiParamDTO, id);
	}

	/**
	 * 执行api请求
	 *
	 * @param platformApiParamDTO
	 * @param id
	 * @return 请求结果 resultMap.get(DATA_FIELD)
	 */
	public Result<?> getOrderBySdk(PlatformApiParamDTO platformApiParamDTO, String id) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		Map<String, Object> params = new HashMap<>();
		params.put("pageSize", 100);
		params.put("pageNo", 1);
		params.put("businessCode", storeConfig.getStoreUniqueCode());
		params.put("orderNo", id);
		String requestId = platformApiParamDTO.getRequestId();
		Result<?> result = this.executeApi(storeConfig, params, requestId);
		if (!result.isSuccess()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> saleDataMap = (Map<String, Object>) resultMap.get("data");
		String subCode = MapUtil.getStr(saleDataMap, "subCode");
		if (!"000".equals(subCode)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003, requestId, this.getPlatformCode()
					, this.getMeioneMethod(), JacksonTool.toJson(resultMap));
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg));
		}
		Map subDataMap = MapUtil.get(saleDataMap, "subData", Map.class);
		List recordsList = MapUtil.get(subDataMap, "records", List.class);
		if (CollUtil.isEmpty(recordsList)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, requestId, id);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
		}
		Object sale = recordsList.get(0);
		if (sale == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, requestId, id);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
		}
		return Result.success().addData(sale);
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param orderGetDTO         接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		if (orderGetDTO == null || platformApiParamDTO.getStoreConfig() == null || StrUtil.isBlank(orderGetDTO.getOrderId())) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), orderGetDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}


}
